package com.wdl.webserver.api;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wdl.webserver.data.CodeCache;

@Service
public class CacheService {
    private static final Logger LOG = LoggerFactory.getLogger(CacheService.class);

    private Map<String, CodeCache> cache = new ConcurrentHashMap<String, CodeCache>();

    public void updateCode(String phoneNumber, String number) {
        CodeCache item = cache.get(phoneNumber);
        if (item == null) {
            item = new CodeCache();
            item.setCode(number);
            item.setTime(System.currentTimeMillis());
        } else {
            item.setCode(number);
            item.setTime(System.currentTimeMillis());
        }

        cache.put(phoneNumber, item);
    }

    public String getCode(String phoneNumber){
        CodeCache myCache = cache.get(phoneNumber);
        return myCache == null ? "" : myCache.getCode();
    }

    @PostConstruct
    public void init() {
        long halfHour = 30 * 60 * 1000;
        int interval = 5;
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                LOG.info("Before routine clean up, code cache size is: " + cache.size());
                for (Entry<String, CodeCache> entry : cache.entrySet()) {
                    CodeCache item = entry.getValue();
                    if ((System.currentTimeMillis() - item.getTime()) > halfHour) {
                        // remove this entry
                        cache.remove(entry.getKey());
                    }
                }
                LOG.info("After routine clean up, code cache size is: " + cache.size());
            } catch (Exception e) {
            }
        }, interval, interval, TimeUnit.MINUTES);
    }
}
